﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Drawing;

namespace Toolbox.Plugin
{
    public class PluginItem
    {
        public string Description { get; private set; }
        public string Category { get; private set; }
        public Image Image { get; private set; }
        public IPlugin Plugin { get; private set; }

        public PluginItem(IPlugin p)
        {
            this.Plugin = p;
            this.Description = GetAttribute<PluginDescriptionAttribute>().Description;
            this.Category = GetAttribute<PluginCategoryAttribute>().Category;

            Type PluginType = this.Plugin.GetType();
            foreach (string ressource in PluginType.Assembly.GetManifestResourceNames())
            {
                //if (ressource.Contains(PluginType.Name) || ressource.Contains(PluginType.Namespace))
                //{
                //    this.Image = Bitmap.FromStream(PluginType.Assembly.GetManifestResourceStream(ressource));
                //    break;
                //}
            }
        }

        public void Configure()
        {
            System.Configuration.Configuration o = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            var p = o.GetSectionGroup("applicationSettings");

            if (p is ConfigurationSectionGroup)
            {
                foreach (ClientSettingsSection s in p.Sections)
                {
                    if (s.SectionInformation.Name.StartsWith(this.Plugin.GetType().FullName))
                    {
                       foreach(SettingElement se in s.Settings)
                       {
                          
                       }

                        break;
                    }
                }
            }
          
        }

        public override string ToString()
        {
            return this.Description;
        }


        public static IEnumerable<PluginItem> FromPluginList(IEnumerable<IPlugin> list)
        {
            List<IPlugin> l = new List<IPlugin>(list);
            return l.ConvertAll(p => new PluginItem(p));
        }

        public T GetAttribute<T>() where T : Attribute
        {
            return GetAttributes<T>().FirstOrDefault() ?? System.Activator.CreateInstance<T>();
        }

        public T[] GetAttributes<T>() where T : Attribute
        {
            object[] Attributes = this.Plugin.GetType().GetCustomAttributes(typeof(T), true);

            return Array.ConvertAll<object, T>(Attributes, a => (T)a).ToArray();
                

        }
    }
}
